import json

from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from rest_framework.response import Response

from .models import Configures
from .serializers import ConfigureSerializer
from utils import handle_datas

class ConfiguresViewSet(ModelViewSet):
    """
    list:
    返回配置信息(多个)列表数据

    create:
    创建配置信息

    retrieve:
    返回配置信息(单个)详情数据

    update:
    更新(全部)配置信息

    partial_update:
    更新(部分)配置信息

    destroy:
    删除配置信息
    """
    queryset = Configures.objects.filter(is_delete=False)
    serializer_class = ConfigureSerializer
    permission_classes = [permissions.IsAuthenticated, ]
    ordering_fields = ('id', 'name')

    def perform_destroy(self, instance):
        instance.is_delete = True
        instance.save()     # 逻辑删除

    def retrieve(self, request, *args, **kwargs):
        config_obj = self.get_object()
        config_request = json.loads(config_obj.request, encoding='utf-8')

        # 处理请求头数据
        config_headers = config_request['config']['request'].get('headers')
        config_hraders_list = handle_datas.handle_data4(config_headers)

        # 处理全局变量数据
        config_variables = config_request['config'].get('variables')
        config_variables_list = handle_datas.handle_data4(config_variables)

        config_name = config_request['config'].get('name')

        datas = {
            'configure_name': config_obj.name,
            'project_id': config_obj.project_id,
            'header': config_hraders_list,
            'variables': config_variables_list
        }
        return Response(datas)





